<?php
/*
* Author：鑫宇工作室
* QQ：639519801
* url：www.xinyuream.com
*/

//检测攻击
waf();



function getRandomNickname()
{
    $qianzhui = [
        '美丽的',
        '聪明的',
        '聪慧的',
        '睿智的',
        '呆呆的',
        '漂亮的',
        '腹黑的',
        '气愤的',
        '白的',
        '天真的',
        '潇洒的',
        '无语的',
        '黑的',
        '红的',
        '黄的',
        '粉的',
        '绿的',
        '紫的',
        '快的',
        '快枪手',
        '王者',
        '青铜',
    ];

    $nicknames = [
        "糖果大盗",
        "梦幻旋律",
        "快乐小丸子",
        "超级披萨侠",
        "星际拼图王",
        "茶叶蛋特工",
        "雷电闪客",
        "跳舞的火龙果",
        "暗夜小猫侠",
        "果汁忍者",
        "闪光的奇迹",
        "小小蓝天使",
        "魔法小辣椒",
        "爆笑大白菜",
        "咖啡因小怪兽",
        "玩具总动员",
        "蜜糖小魔女",
        "钢铁侠的表弟",
        "彩虹小飞侠",
        "奇异果超人",
        "雷霆火箭猫",
        "太空披萨使者",
        "蓝色海豚梦",
        "旋风小呆瓜",
        "糖果巡警队",
        "快乐旋律师",
        "魔法蘑菇精",
        "摇滚小企鹅",
        "虚空小狐狸",
        "霓虹星辰梦",
        "幸运小狸猫",
        "魔法雪花精",
        "软绵绵大白",
        "梦幻彩虹风",
        "小小星际舰长",
        "炸弹冰淇淋",
        "跳跃的奇迹",
        "美梦小猫仙",
        "音乐蝴蝶梦",
        "果冻甜心宝",
        "电光火石狂魔",
        "梦幻宇航员",
        "喜笑颜开小丸子",
        "独角兽奇迹",
        "彩虹梦游者",
        "旋风小快递",
        "摇滚狂热者",
        "幽灵舞者",
        "翻滚果冻怪",
        "星际蓝天使",
        "飞天小猪侠",
        "极光小精灵",
        "追梦小火箭",
        "奇幻糖果王",
        "蜜蜂舞者",
        "冰雪甜心仙",
        "小小海盗王",
        "夜空流星雨",
        "闪耀音符精灵",
        "草原小精灵"
    ];

    // 从数组中随机选择一个元素
    $randomNickname = $qianzhui[array_rand($qianzhui)].$nicknames[array_rand($nicknames)];

    return $randomNickname;
}

//循环创建目录
function mkdirs($dir, $mode = 0777)
{
    if (!is_dir($dir)) {
        mkdirs(dirname($dir), $mode);
        return mkdir($dir, $mode);
    }
    return true;
}

function get_host(){
    $host = $_SERVER["HTTP_HOST"];
    $protocol = isSsl() ? "https://" : "http://";
    return $protocol.$host;

}

function isSsl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } elseif ('https' == @$_SERVER['REQUEST_SCHEME']) {
        return true;
    } elseif ('443' == @$_SERVER['SERVER_PORT']) {
        return true;
    } elseif ('https' == @$_SERVER['HTTP_X_FORWARDED_PROTO']) {
        return true;
    }
    return false;
}

function get_card_type($num,$bool=false){
	$str="";
	$n=1;
	if($num==4){
		$str="年卡";
		$n=365;
	}elseif($num==3){
		$str="月卡";
		$n=30;
	}elseif($num==2){
		$str="周卡";
		$n=7;
	}else{
		$str="天卡";
		$n=1;
	}
	if($bool){
		return $n;
	}
	return $str;
}

function insertlog($username,$type,$uid=0){
	$ip=get_ip();
	$ipaddr=get_ipaddr($ip);
    if(!$uid){
        $uid = isset($_SESSION['admin_id'])?$_SESSION['admin_id']:0;
    }
	$sql="insert into xy_log(`username`,`logtime`,`logip`,`ipaddr`,`logtype`,`uid`)value('{$username}',now(),'{$ip}','{$ipaddr}','{$type}','{$uid}')";
	query($sql,2);
}

function config($str){
	$sql="select svalue from xy_config where skey='{$str}'";
	$re=query($sql);
	if($re){
		return $re[0]['svalue'];
	}
	return '';
}

function xiaoxie($str){
	return strtolower($str);
}

function daxie($str){
	return strtoupper($str);
}
function apijson($code,$msg){
	global $dtype;
	if($dtype !=''){
		echo $code.$dtype.$msg;
		exit;
	}else{
		header("Content-type:application/json");
		echo json_encode(array('code'=>$code,"msg"=>$msg));
		exit;
	}
}

function json($arr){
	header("Content-type:application/json");
	echo json_encode($arr,256);
	exit;
}
function input($str){
	if(isset($_GET[$str])){
		return $_GET[$str];
	}elseif(isset($_POST[$str])){
		return $_POST[$str];
	}else{
		return '';
	}
}


// 此方法 会被火绒查杀
function waf(){
    $str= [
		'\'',
        '\.\./', //禁用包含 ../ 的参数
        '\<\?', //禁止php脚本出现
        '\s*or\s+.*=.*', //匹配' or 1=1 ,防止sql注入
        'select([\s\S]*?)(from|limit)', //防止sql注入
        '(?:(union([\s\S]*?)select))', //防止sql注入
        'having|updatexml|extractvalue', //防止sql注入
        'sleep\((\s*)(\d*)(\s*)\)', //防止sql盲注
        'benchmark\((.*)\,(.*)\)', //防止sql盲注
        'base64_decode\(', //防止sql变种注入
        '(?:from\W+information_schema\W)', //防止sql注入
        '(?:(?:current_)user|database|schema|connection_id)\s*\(', //防止sql注入
        '(?:etc\/\W*passwd)', //防止窥探linux用户信息
        'into(\s+)+(?:dump|out)file\s*', //禁用mysql导出函数
        'group\s+by.+\(', //防止sql注入
        '(?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\(', //禁用webshell相关某些函数
        '(gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\/', //防止一些协议攻击
        '\$_(GET|post|cookie|files|session|env|phplib|GLOBALS|SERVER)\[', //禁用一些内置变量,建议自行修改
        '\<(iframe|script|body|img|layer|div|meta|style|base|object|input)', //防止xss标签植入
        '(onmouseover|onerror|onload|onclick)\=', //防止xss事件植入
        '\|\|.*(?:ls|pwd|whoami|ll|ifconfog|ipconfig|&&|chmod|cd|mkdir|rmdir|cp|mv)', //防止执行shell （这句存在关键词会被查杀）
        '\s*and\s+.*=.*' //匹配 and 1=1
    ];
	if(!isset($_SERVER['REQUEST_URI'])){
		$_SERVER['REQUEST_URI']='';
	}
	if(!isset($_SERVER['HTTP_COOKIE'])){
		$_SERVER['HTTP_COOKIE']='';
	}
	 $re=query("select * from information_schema.TABLES where TABLE_NAME = 'lock_ip_wfa'");
	if(!$re){
		query("CREATE TABLE `lock_ip_wfa` (`id` int(11) NOT NULL AUTO_INCREMENT,`ip` varchar(15) NOT NULL,`time` datetime NOT NULL,`url` varchar(255) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `ip` (`ip`) USING BTREE) ENGINE=MyISAM DEFAULT CHARSET=utf8;",2);
	}
	$ip=get_ip();
    $data = urldecode($_SERVER['REQUEST_URI']).urldecode($_SERVER['HTTP_COOKIE']) .urldecode(file_get_contents('php://input')).implode('', getallheaders());
    foreach ($str as $rule) {
        if (preg_match('^' . $rule . '^i', $data)) {
			if($ip !='unknown' && !query("select id from lock_ip_wfa where ip='{$ip}'")){
				query("insert into lock_ip_wfa(`ip`,`url`,`time`)value('{$ip}','".addslashes($rule)."',now())",2);
			}
            error_exit();
        }
    }
	if($ip !='unknown' && query("select id from lock_ip_wfa where ip='{$ip}'")){
		error_exit();
	}
}



function get_ipaddr($ip){
	if ($ip == '::1'){
		$add = 'IANA保留地址';
	}elseif($ip=='unknown'){
		$add='未知地址';
	}else{
		include_once($_SERVER['DOCUMENT_ROOT'].'/func/iplocation.php');
		$format = "text";//默认text,json,xml,js
		$charset = "utf8"; //默认utf-8,gbk或gb2312
		$ip_l=new ipLocation();
		$address=$ip_l->getaddress($ip);
		$address["area1"] = iconv('GB2312','utf-8',$address["area1"]);
		$address["area2"] = iconv('GB2312','utf-8',$address["area2"]);
		$add=$address["area1"]."·".$address["area2"];
	}
	return $add;
}


function get_ip(){
	global $cdnagent;
	if($cdnagent !='' && isset($_SERVER[$cdnagent]) && $_SERVER[$cdnagent] && strcasecmp($_SERVER[$cdnagent],"unknown")){
		$ip = $_SERVER[$cdnagent];
	}elseif(isset($_SERVER["HTTP_CLIENT_IP"]) && $_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")){
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}elseif(isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown")){
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],"unknown")){
        $ip = $_SERVER['REMOTE_ADDR'];
    }else{
        $ip = "unknown";
    }
    $arr=explode(",",$ip);
    if(count($arr)>0){
        $ip=$arr[0];
    }
	if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/',$ip) && strlen($ip)<=15){
		return $ip;
	}else{
		return 'unknown';
	}
}


function pwdMd5($text,$at='zxc图uu'){
    return md5(md5($text.$at));
}

/**
 * spAccess 数据缓存及存取程序
 *
 * @param method    数据存取模式，取值"w"为存入数据，取值"r"读取数据，取值"c"为删除数据
 * @param name    标识数据的名称
 * @param value    存入的值，在读取数据和删除数据的模式下均为NULL
 * @param life_time    变量的生存时间，默认为永久保存
 */
function spAccess($method, $name, $value = NULL, $life_time = -1)
{
    // 准备缓存目录和缓存文件名称，缓存文件名称为$name的MD5值，文件后缀为php
    $sp_cache = APP.'/runtime/cache/';
    if (!is_dir($sp_cache)) mkdirs($sp_cache);
    $sfile = $sp_cache . '/' . md5($name) . ".php";
    // 对$method进行判断，分别进行读写删的操作
    if ('w' == $method) {
        // 写数据，在$life_time为-1的时候，将增大$life_time值以令$life_time不过期
        $life_time = (-1 == $life_time) ? '300000000' : $life_time;
        // 准备存入缓存文件的数据，缓存文件使用PHP的die();函数以便保证内容安全，
        $value = '<?php die();?>' . (time() + $life_time) . serialize($value); // 数据被序列化后保存
        return file_put_contents($sfile, $value);
    } elseif ('c' == $method) {
        // 清除数据，直接移除改缓存文件
        return @unlink($sfile);
    } else {
        // 读数据，检查文件是否可读，同时将去除缓存数据前部的内容以返回
        if (!is_readable($sfile)) return FALSE;
        $arg_data = file_get_contents($sfile);
        // 获取文件保存的$life_time，检查缓存是否过期
        if (substr($arg_data, 14, 10) < time()) {
            @unlink($sfile); // 过期则移除缓存文件，返回FALSE
            return FALSE;
        }
        return unserialize(substr($arg_data, 24)); // 数据反序列化后返回
    }

}

/**
 * 获取 多少分钟后
 * @param $time
 * @return void
 */
function getDateAfter($time=null){
    if(!is_numeric($time)){
        $time = strtotime($time);
    }
    $diff = $time - time();
    if($diff<0) return '已过期';
    switch ($diff){
        case $diff<3600:$text=floor($diff/60).'分钟';break;
        case $diff<86400*3:$text=floor($diff/60/60).'小时';break;
        case $diff<86400*90:$text=floor($diff/60/60/24).'天';break;
        default:$text=floor($diff/60/60/24/30).'月';break;
    }
    return $text;
}
/**
 * 获取时间 N分钟前
 * @param $time
 * @param $type  1 N分钟前  2 N分钟后
 * @return false|string
 */
function getDateText($time = NULL,$type=1) {
    if(!is_numeric($time)){
        $time = strtotime($time);
    }
    $text = '';
    if($type==1){
        $time = $time === NULL || $time > time() ? time() : intval($time);
        $t = time() - $time; //时间差 （秒）
        $y = date('Y', $time)-date('Y', time());//是否跨年
    }else{
        return getDateAfter($time);
    }

    $ext = $type==1?'前':'后';
    switch($t){
        case $t == 0:
            $text = $type==1?'刚刚':'立刻';
            break;
        case $t < 60:
            $text = $t . '秒'.$ext; // 一分钟内
            break;
        case $t < 60 * 60:
            $text = floor($t / 60) . '分钟'.$ext; //一小时内
            break;
        case $t < 60 * 60 * 24:
            $text = floor($t / (60 * 60)) . '小时'.$ext; // 一天内
            break;
        case $t < 60 * 60 * 24 * 3:
            if($type==1){
                $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
            }else{
                $text = floor($time/(60*60*24)) ==1 ?'明天 ' . date('H:i', $time) : '后天 ' . date('H:i', $time) ; //昨天和前天
            }
            break;
        case $t < 60 * 60 * 24 * 30:
            $text = date('m月d日 H:i', $time); //一个月内
            break;
        case $t < 60 * 60 * 24 * 365&&$y==0:
            $text = date('m月d日', $time); //一年内
            break;
        default:
            $text = date('Y年m月d日', $time); //一年以前
//            $text = $t;
            break;
    }
    return $text;
}
function error_exit(){
	@header("http/1.1 404 not found");
    @header("status: 404 not found");
	echo '<html>
	<head><title>404 Not Found</title></head>
	<body>
	<center><h1>404 Not Found</h1></center>
	<hr><center>nginx</center>
	</body>
	</html>';
	exit;
}



function err($msg){
    $msg = htmlspecialchars($msg);
    $traces = debug_backtrace();
    if(!empty($GLOBALS['err_handler'])){
        call_user_func($GLOBALS['err_handler'], $msg, $traces);
    }else{
        if(isset($GLOBALS['app_debug']) && !$GLOBALS['app_debug']){
            // 将错误输出到日志中
            echo "<div> <h4>{$msg}</h4> 位于 {$traces[0]['file']} line：{$traces[0]['line']}</div>";
        }else{
            if (ob_get_contents()) ob_end_clean();
            function _err_highlight_code($code)
            {
                if (preg_match('/\<\?(php)?[^[:graph:]]/i', $code)) {
                    return highlight_string($code, TRUE);
                } else {
                    return preg_replace('/(&lt;\?php&nbsp;)+/i', "", highlight_string("<?php " . $code, TRUE));
                }
            }
            function _err_getsource($file, $line)
            {
                if (!(file_exists($file) && is_file($file))) {
                    return '';
                }
                $data = file($file);
                $count = count($data) - 1;
                $start = $line - 5;
                if ($start < 1) {
                    $start = 1;
                }
                $end = $line + 5;
                if ($end > $count) {
                    $end = $count + 1;
                }
                $returns = array();
                for ($i = $start; $i <= $end; $i++) {
                    if ($i == $line) {
                        $returns[] = "<div id='current'>" . $i . ".&nbsp;" . _err_highlight_code($data[$i - 1], TRUE) . "</div>";
                    } else {
                        $returns[] = $i . ".&nbsp;" . _err_highlight_code($data[$i - 1], TRUE);
                    }
                }
                return $returns;
            }?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta name="robots" content="noindex, nofollow, noarchive"/>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <title><?php echo $msg; ?></title>
            <style>body {
                    padding: 0;
                    margin: 0;
                    word-wrap: break-word;
                    word-break: break-all;
                    font-family: Courier, Arial, sans-serif;
                    background: #EBF8FF;
                    color: #5E5E5E;
                }

                div, h2, p, span {
                    margin: 0;
                    padding: 0;
                }

                ul {
                    margin: 0;
                    padding: 0;
                    list-style-type: none;
                    font-size: 0;
                    line-height: 0;
                }

                #body {
                    width: 918px;
                    margin: 0 auto;
                }

                #main {
                    width: 918px;
                    margin: 13px auto 0 auto;
                    padding: 0 0 35px 0;
                }

                #contents {
                    width: 918px;
                    float: left;
                    margin: 13px auto 0 auto;
                    background: #FFF;
                    padding: 8px 0 0 9px;
                }

                #contents h2 {
                    display: block;
                    background: #CFF0F3;
                    font: bold 20px;
                    padding: 12px 0 12px 30px;
                    margin: 0 10px 22px 1px;
                }

                #contents ul {
                    padding: 0 0 0 18px;
                    font-size: 0;
                    line-height: 0;
                }

                #contents ul li {
                    display: block;
                    padding: 0;
                    color: #8F8F8F;
                    background-color: inherit;
                    font: normal 14px Arial, Helvetica, sans-serif;
                    margin: 0;
                }

                #contents ul li span {
                    display: block;
                    color: #408BAA;
                    background-color: inherit;
                    font: bold 14px Arial, Helvetica, sans-serif;
                    padding: 0 0 10px 0;
                    margin: 0;
                }

                #oneborder {
                    width: 800px;
                    font: normal 14px Arial, Helvetica, sans-serif;
                    border: #EBF3F5 solid 4px;
                    margin: 0 30px 20px 30px;
                    padding: 10px 20px;
                    line-height: 23px;
                }

                #oneborder span {
                    padding: 0;
                    margin: 0;
                }

                #oneborder #current {
                    background: #CFF0F3;
                }</style>
        </head>
        <body>
        <div id="main">
            <div id="contents"><h2><?php echo $msg ?></h2><?php foreach ($traces as $trace) {
                    if (is_array($trace) && !empty($trace["file"])) {
                        $souceline = _err_getsource($trace["file"], $trace["line"]);
                        if ($souceline) { ?>
                            <ul>
                                <li><span><?php echo $trace["file"]; ?> on line <?php echo $trace["line"]; ?> </span></li></ul>
                            <div id="oneborder"><?php foreach ($souceline as $singleline) echo $singleline; ?></div><?php }
                    }
                } ?></div>
        </div>
        <div style="clear:both;padding-bottom:50px;"/>
        </body>
            </html><?php }
        exit;
    }
}

?>